/*
 * Copyright (C) 2010 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.zxing.client.ohos;

import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.CommonEventSupport;
import ohos.event.commonevent.MatchingSkills;
import ohos.event.commonevent.CommonEventSubscriber;
import ohos.event.commonevent.CommonEventData;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.rpc.RemoteException;

/**
 * Finishes an context after a period of inactivity if the device is on battery power.
 */
public final class InactivityTimer {

    private static final long INACTIVITY_DELAY_MS = 5 * 60 * 1000L;

    private final Context context;
    private final PowerStatusReceiver powerStatusReceiver;
    private boolean registered = false;
    private EventHandler handler;
    private Runnable callback;
    private boolean onBattery;

    public InactivityTimer(Context context, Runnable callback) {
        this.context = context;
        this.callback = callback;

        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_BATTERY_CHANGED);
        CommonEventSubscribeInfo eventSubscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        powerStatusReceiver = new PowerStatusReceiver(eventSubscribeInfo);
        handler = new EventHandler(EventRunner.getMainEventRunner());
    }

    /**
     * Trigger Ability, resetting the timer.
     */
    public void activity() {
        cancelCallback();
        if (onBattery) {
            handler.postTask(callback, INACTIVITY_DELAY_MS);
        }
    }

    /**
     * Start the Ability timer.
     */
    public void start() {
        registerReceiver();
        activity();
    }

    /**
     * Cancel the Ability timer.
     */
    public void cancel() {
        cancelCallback();
        unregisterReceiver();
    }

    private void unregisterReceiver() {
        if (registered) {
            try {
                CommonEventManager.unsubscribeCommonEvent(powerStatusReceiver);
                registered = false;
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void registerReceiver() {
        if (!registered) {
            try {
                CommonEventManager.subscribeCommonEvent(powerStatusReceiver);
                registered = true;
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void cancelCallback() {
        handler.removeAllEvent();
    }

    private void onBattery(boolean onBattery) {
        this.onBattery = onBattery;

        // To make sure we're still running
        if (registered) {
            // This will either cancel or reschedule, depending on the battery status.
            activity();
        }
    }

    private final class PowerStatusReceiver extends CommonEventSubscriber {

        public PowerStatusReceiver(CommonEventSubscribeInfo subscribeInfo) {
            super(subscribeInfo);
        }

        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
            Intent intent = commonEventData.getIntent();
            if (CommonEventSupport.COMMON_EVENT_BATTERY_CHANGED.equals(intent.getAction())) {
                // 0 indicates that we're on battery
                final boolean onBatteryNow = intent.getIntParam("plugged", -1) <= 0;
                // post on handler to run in main thread
                handler.postTask(() -> onBattery(onBatteryNow));
            }
        }
    }
}
